package com.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebListener
public class OnlineCountListener implements HttpSessionListener, ServletContextListener {
    
    // 记录在线人数
    private static int onlineCount = 0;
    
    /**
     * Session创建时执行
     */
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        onlineCount++;
        // 将在线人数保存到ServletContext中
        ServletContext context = se.getSession().getServletContext();
        context.setAttribute("onlineCount", onlineCount);
        System.out.println("新用户上线，当前在线人数：" + onlineCount);
    }

    /**
     * Session销毁时执行
     */
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        onlineCount--;
        if(onlineCount < 0) {
            onlineCount = 0;
        }
        ServletContext context = se.getSession().getServletContext();
        context.setAttribute("onlineCount", onlineCount);
        System.out.println("用户下线，当前在线人数：" + onlineCount);
    }

    /**
     * 服务器启动时执行
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = sdf.format(new Date());
        context.setAttribute("serverStartTime", startTime);
        System.out.println("系统启动时间：" + startTime);
        
        // 初始化在线人数
        context.setAttribute("onlineCount", 0);
    }

    /**
     * 服务器关闭时执行
     */
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String shutdownTime = sdf.format(new Date());
        System.out.println("系统关闭时间：" + shutdownTime);
    }
} 